// import WeboSocket library
var WebSocketServer = require('ws').Server;
// create a websocket server at port 8080
var wss = new WebSocketServer({port:8080});
// all connected to the server users
var users = {};
// when a user connect to our server
wss.on('connection',function(connection){
	console.log('user connected');
	connection.on('message',function(message){
		// format JSON data
		var data;
		try {
			data = JSON.parse(message);
		} catch(e) {
			console.log('Invilid JSON');
			data={};
		}
		console.log('Got message from a user: ',message);
		switch(data.type) {
			case 'login':
				console.log('user logged:',data.name);
				// if anyone logged in with this username then refuse
				if(users[data.name]) {
					sendTo(connection,{
						type: 'login',
						success: false
					})
				} else {
					// save user connection on the server
					users[data.name] = connection;
					connection.name = data.name;
					sendTo(connection,{
						type: 'login',
						success: true
					})
				}
				break;
			case 'offer':
				// userA want call userB
				console.log('Sending offer to: ' , data.name);
				// if userB exist,then send him offer detail
				var conn = users[data.name];
				if( conn != null ) {
					// setting userA connected with userB
					connection.otherName = data.name;
					sendTo(conn,{
						type: 'offer',
						offer: data.offer,
						name: connection.name
					});
				}
				break;
			case 'answer':
				console.log('Sending answer to: ',data.name);
				// for ex,userB answers userA
				var conn = users[data.name];
				if( conn != null) {
					connection.otherName = data.name;
					sendTo(conn,{
						type: 'answer',
						answer: data.answer
					})
				}
				break;
			case 'candidate':
				console.log('Sending candidate to:',data.name);
				var conn = users[data.name];
				if( conn != null) {
					sendTo(conn,{
						type: 'candidate',
						candidate: data.candidate
					})
				}
				break;
			case 'leave':
				console.log('Disconnecting from:',data.name);
				var conn = users[data.name];
				conn.otherName = null;
				if(conn != null) {
					sendTo(conn,{
						type: 'leave'
					})
				}
				break;
			default:
				sendTo(connection,{
					type: 'error',
					message: 'Command not found: ' + data.type
				});
				break;
		}
	});
	// when user close connection
	connection.on('close',function(){
		if(connection.name) {
			delete users[connection.name];
			if(connection.otherName) {
				console.log('Sending from:',data.name[otherName]);
				var conn = users[connection.otherName];
				conn.otherName = null;
				if( conn != null) {
					sendTo(conn,{
						type: 'leave'
					})
                }
            }
		}
	});
	connection.send('Hello from server');
});

function sendTo(connection,message){
	connection.send(JSON.stringify(message));
}